package servicios.biziGasteiz;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import connection.BDConnection;

/**
 * Servlet implementation class ConcertsServices
 */
public class FilterServices extends HttpServlet {
	private static final long serialVersionUID = 1L;

    private String CONTENT_TYPE = "text/json";
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FilterServices() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {

			processRequest(request, response);

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			e.printStackTrace();
		}
	}
	
	
	
	private void processRequest(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		response.setContentType(CONTENT_TYPE);
		String requestP = request.getParameter("request");
		try{
			if(requestP.compareToIgnoreCase("GETCOMBODATA") == 0){
				getComboData(request, response);
			}
			else if(requestP.compareToIgnoreCase("GETRESTAURANTSBYFILTER") == 0){
				getRestaurantsByFilter(request, response);
			}
		}catch(Exception e){
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			e.printStackTrace();
		}
	}
	
	private void getComboData(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			String sqlQuery = request.getParameter("query");
			ResultSet rs = bdCon.executeQuery(sqlQuery);
			JSONArray resJsonArray = new JSONArray();
			while(rs.next()){
				JSONObject item = new JSONObject();
				item.put("text", rs.getString("text"));
				item.put("value", rs.getString("value"));
				resJsonArray.put(item);
			}
			JSONObject resJson = new JSONObject();
			resJson.put("success", true);
			resJson.put("data", resJsonArray);
			print.write(resJson.toString());
			bdCon.closeConnection(rs);
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());
			
		}
	}
	
	private void getRestaurantsByFilter(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String sql = request.getParameter("query");
			System.out.println(sql);
			ResultSet rs = bdCon.executeQuery(sql);
			
			JSONArray resJsonArray = new JSONArray();

			while(rs.next()){
				JSONObject itemJson = new JSONObject();
				itemJson.put("nombre", rs.getString("nombre"));
				itemJson.put("descripcion_corta", rs.getString("descripcion_corta"));
				itemJson.put("tipo", rs.getString("tipo"));
				itemJson.put("foto_principal", rs.getString("foto_principal"));
				itemJson.put("localizacion", rs.getString("localizacion"));
				itemJson.put("horario", rs.getString("horario"));
				itemJson.put("restaurantid", rs.getInt("restaurantid"));
				itemJson.put("descripcion", rs.getString("descripcion"));
				itemJson.put("calle", rs.getString("calle"));
				JSONArray menuJsonArray = new JSONArray();
				String sqlMenu = "SELECT * FROM MENU WHERE restauranteid='"+rs.getInt("restaurantid")+"'";
				ResultSet rs1 = bdCon.executeQuery(sqlMenu);
				while(rs1.next()){
					JSONObject menuJson = new JSONObject();
					menuJson.put("restauranteid", rs1.getString("restauranteid"));
					menuJson.put("precio", rs1.getDouble("precio"));
					menuJson.put("descripcion", rs1.getString("descripcion"));
					menuJson.put("menuid", rs1.getInt("menuid"));
					menuJson.put("foto", rs1.getString("foto"));
					menuJson.put("nombre", rs1.getString("nombre"));
					menuJson.put("tipo", rs1.getString("tipo"));
					menuJsonArray.put(menuJson);
				}
				itemJson.put("menus", menuJsonArray);
				resJsonArray.put(itemJson);
			}
			JSONObject resJson = new JSONObject();
			resJson.put("success", true);
			resJson.put("data", resJsonArray);
			
			print.write(resJson.toString());
			bdCon.closeConnection();
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());
			
		}
	}
	
}
